#pragma once

#include <iostream>
#include <math.h>
#include <string>
#include <vector>
#include "mockturtle/mockturtle.hpp"
#include "detail_dsd.hpp"

namespace mockturtle
{
namespace detail
{
template<class Ntk>
signal<Ntk> sel_decomp_impl( Ntk& ntk, std::vector<std::vector<int>>& sel_vec, std::vector<signal<Ntk>> pis_sel )
{	
	kitty::dynamic_truth_table remainder( sel_vec[0].size() );
	for( int j = 0; j < sel_vec.size(); j++ )
	{
		std::string s;
		for( int k = 0; k < sel_vec[j].size(); k++ )
		{
			if( sel_vec[j][k] == -1 )
			{
				sel_vec[j][k] = 1;
				std::vector<int> b;
				b.assign( sel_vec[j].begin(), sel_vec[j].end() );
				sel_vec.push_back( b );
				sel_vec[sel_vec.size() - 1 ][k] = 0;
			}		
			std::string a = std::to_string( sel_vec[j][k] );
			s += a;
		}
		int len = s.length();
		int n = 0;
		for (int i = 0; i < len; i++ )
		{
			if( s[i] == '1' )
			{
				n+=pow( 2, len-1-i );
			}
		}
		kitty::set_bit( remainder, n );
	}
	return mockturtle::dsd_detail( ntk, remainder, pis_sel, "mag"  );
}
}//namespace detail
template<class Ntk>
signal<Ntk> sel_decomp( Ntk& ntk, std::vector<std::vector<int>>& sel_vec, std::vector<signal<Ntk>> pis_sel )
{
	return detail::sel_decomp_impl<Ntk>( ntk, sel_vec, pis_sel );
}

}//namespace mockturtle
